﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace ScoreCaching
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        private string strConnection = ConfigurationManager.ConnectionStrings["ScoreTable"].ToString();
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public void addToDatabase(_scoreTable table)
        {
            using (SqlConnection con = new SqlConnection(strConnection))
            {
                con.Open();
                SqlCommand command = new SqlCommand("insert into ScoreTable(CurrentScore, Name, Country) values(@CurrentScore, @Name, @Country)", con);
                command.Parameters.AddWithValue("@CurrentScore", table.CurrentScore);
                command.Parameters.AddWithValue("@Name", table.Name);
                command.Parameters.AddWithValue("@Country", table.Country);
                int result = command.ExecuteNonQuery();
                if (result == 1)
                {
                    //yay!
                }
                else
                {
                    //:(
                }
                con.Close();
            }
        }

        public List<_scoreTable> Retrieve()
        {
            List<_scoreTable> _scores = new List<_scoreTable>();
            using (SqlConnection con = new SqlConnection(strConnection))
            {
                con.Open();
                SqlCommand command = new SqlCommand("Select * from ScoreTable", con);
                SqlDataAdapter da = new SqlDataAdapter(command);
                DataTable dtresult = new DataTable();
                da.Fill(dtresult);
                if(dtresult.Rows.Count>0)
                {
                    for(int i=0;i<dtresult.Rows.Count;i++)
                    {
                        _scoreTable temp = new _scoreTable();
                        temp.Country = dtresult.Rows[i]["Country"].ToString();
                        temp.CurrentScore = Int16.Parse(dtresult.Rows[i]["CurrentScore"].ToString());
                        temp.Name = dtresult.Rows[i]["Name"].ToString();
                        _scores.Add(temp);
                    }
                }
                con.Close();      
            }
            return _scores;

            }
        
        }
    }

